import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UserEntity } from "./user.entity";

export interface UserRo {
  list: UserEntity[];
  count: number;
}
@Injectable()
export class UserService {
  constructor( @InjectRepository(UserEntity)
  private UserRepository:Repository<UserEntity>){}

  async create(body:any) {
    const phone = body?.phone;
    const count = await this.UserRepository.count({
      where: {
        phone: phone
      }
    })
    if (count !== 0) {
      return {
        status:1,
        title:"已存在该用户",
        count,
      }
    }else {
      const count = await this.UserRepository.count({
      })
      const user = {
        id:count + 1,
        name: body?.name,
        phone: body?.phone,
        password: body?.password,
        role:body?.role
      }
      this.UserRepository.save(user)
      return {
        status:0,
        title:"添加成功",
        count,
        user
      }

    }
    
  }

  async findAll() {
    const list = await this.UserRepository.find()
    const count = await this.UserRepository.count()
    return {
      list,
      count
    }
  }
  async login(body:any) {
    const phone = body?.phone
    const password = body?.password
    const user = await this.UserRepository.findOne({
      where:{
        phone,
        password
      }
    })
    const count = await this.UserRepository.count({
      where:{
        phone,
        password
      }
    })
    if (count === 0) {
      return {
        status:1,
        title:"账号密码错误"
      }
    }else {
      return {
        status:0,
        title:"登录成功",
        data:user
      }
    }
  }
  async like(body:any) {
    const userId = body?.userId
    const houseId = body?.houseId
    const user = await this.UserRepository.findOne({
      where:{
        id:userId
      }
    })
    console.log(user);
    if (user) {
      // 保存房子id
      if (!user.like) {
        let arr = []
        arr.push(houseId)
        user.like = JSON.stringify(arr)
        await this.UserRepository.save(user)
      }else {
        let arr = JSON.parse(user.like)
        if (!arr.includes(houseId)) {
          arr.push(houseId)
          user.like = JSON.stringify(arr)
          await this.UserRepository.save(user)
        }else {
          arr = arr.filter((item)=>{
            return item !== houseId
          })
          user.like = JSON.stringify(arr)
          await this.UserRepository.save(user)
        }
      }

    }
  }
  async getLike(body:any){
    const userId = body?.userId
    const user = await this.UserRepository.findOne({
      where:{
        id:userId
      }
    })
    return {
      status:0,
      data:JSON.parse(user.like)
    }
  }
  update(id: number) {
    return `This action updates a #${id} user`;
  }

}
